package com.auto.api.mapping.listener;

import com.auto.api.mapping.component.ApiInfoManager;
import com.auto.api.core.util.SpringContextHolder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * Description: spring容器初始化完成后，启动加载mapping映射
 *
 * @author liangshf
 * @date 2019年6月13日
 */
public class MappingInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${auto.api.mapping:false}")
    private boolean enableMapping;

    /**
     * 是否已经初始化过了，确保只初始化一次
     */
    private static volatile boolean initialled = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //通过判断是否为根applicationContext（没有父级）来防止下面的代码多次执行，
        //因为还有可能有其他子applicationContext存在。
        if (!enableMapping) {
            return;
        }
        synchronized (ApiInfoManager.class) {
            if (event.getApplicationContext().getParent() != null && initialled) {
                return;
            }
            initialled = true;
        }
        ApplicationContext context = event.getApplicationContext();
        //设置容器上下文
        SpringContextHolder.setApplicationContext(context);
        ApiInfoManager apiInfoManager = (ApiInfoManager) context.getBean("apiInfoManager");
        apiInfoManager.processApiList();
    }

}
